package com.leyou.order.service;

import com.leyou.common.auth.pojo.UserHolder;
import com.leyou.common.constants.LyConstants;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.client.ItemClient;
import com.leyou.item.entity.Sku;
import com.leyou.order.utils.Collect;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CollectService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ItemClient itemClient;

    /**
     * 点击关注，添加到收藏夹中
     * 收藏夹放到Redis中
     * */
    public Boolean save(Collect collect) {
        String s = UserHolder.getUserId().toString();
        //将当前用户进行关注的商品放到Redis缓存中
        String key = LyConstants.COLLECT_PRE + s;
        //当前价格和收藏时价格一样
        collect.setCollectPrice(collect.getPrice());
        try{
            //获取key（键+用户id）
            BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
            //得到新添加收藏对象的hashkey  skuId作为hashkey
            String hashKey = collect.getSkuId().toString();
            //保存到Redis中
            hashOps.put(hashKey, JsonUtils.toString(collect));
            return true;
        }catch (Exception e){
            log.error("【Redis添加收藏】失败");
        }
        return false;
    }

    /**
     * 查询我的收藏
     * */
    public List<Collect> findCollect() {
        //得到当前用户在Redis中存放收藏的key
        String key = LyConstants.COLLECT_PRE + UserHolder.getUserId();
        //通过key得到对应的hash
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        //判断是否有收藏数据
        if (hashOps == null || hashOps.size() == 0){
            throw new LyException(404,"收藏信息不存在！");
        }
        //如果有将收藏信息拿出来
        List<Collect> collect1 = hashOps.values()
                .stream()
                .map(collect -> JsonUtils.toBean(collect, Collect.class))
                .collect(Collectors.toList());
        return collect1;
    }


    /**
     * 修改Redis对应的收藏信息，是否降价通知
     * */
    public String updateNotice(Collect collect) {
        String key = LyConstants.COLLECT_PRE + UserHolder.getUserId();
        Long skuId = collect.getSkuId();

        //获取数库的价格
        Sku sku = itemClient.findSkuById(skuId);

        //获取当前Redis缓存的价格
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        String s = hashOps.get(skuId.toString());
        Collect collect1 = JsonUtils.toBean(s, Collect.class);
        Double sum = (collect1.getCollectPrice() - sku.getPrice())/100.00;
        if (sum > 0) {

            //数据库数据变了，Redis也要更新
            collect1.setPrice(sku.getPrice());
            hashOps.put(skuId.toString(),JsonUtils.toString(collect1));

            return "比收藏时优惠了" + sum + "元";
        }
        else {
            return "暂无优惠！";
        }


    }
}